package com.liang.security.springboot.dao;

import com.liang.security.springboot.model.PermissionDto;
import com.liang.security.springboot.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liang zai
 * @date 2021/9/1 17:34
 * @description
 */
@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据用户名查找用户信息
     *
     * @param username
     * @return
     */
    public UserDto getUserByName(String username) {
        String sql = "select id,username,password,fullname from t_user where username = ?";
        List<UserDto> list = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserDto.class));
        if (list == null && list.size() <= 0) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 根据用户的id查找用户的权限
     *
     * @param userId
     * @return
     */
    public List<String> findPermissionsByUserId(String userId) {
        String sql = "SELECT * FROM t_permission WHERE id IN(\n"
                + "SELECT permission_id FROM t_role_permission WHERE role_id IN(\n"
                + "\tSELECT role_id FROM t_user_role WHERE user_id = ? \n" + ")\n" + ")";
        List<PermissionDto> list = jdbcTemplate.query(sql, new Object[]{userId},
                new BeanPropertyRowMapper<>(PermissionDto.class));

        List<String> permissions = new ArrayList<>();
        list.iterator().forEachRemaining(c -> permissions.add(c.getCode()));
        return permissions;
    }
}
